﻿using DingChiServiceApp.helper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace DingChiServiceApp
{
    public class ServiceHelper
    {

        /// <summary>
        /// 服务是否存在
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static bool IsServiceExisted(string serviceName)
        {
            ServiceController[] services = ServiceController.GetServices();
            foreach (ServiceController s in services)
            {
                if (s.ServiceName == serviceName)
                {
                    return true;
                }
            }
            LogHelper.FileLog(serviceName + " 不存在", true);
            return false;
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="serviceName"></param>
        public static void StartService(string serviceName)
        {
            if (IsServiceExisted(serviceName))
            {
                ServiceController service = new ServiceController(serviceName);
                if (service.Status != ServiceControllerStatus.Running && service.Status != ServiceControllerStatus.StartPending)
                {
                    service.Start();
                    for (int i = 0; i < 60; i++)
                    {
                        service.Refresh();
                        System.Threading.Thread.Sleep(1000);
                        if (service.Status == ServiceControllerStatus.Running)
                        {
                            break;
                        }
                        if (i == 59)
                        {
                            LogHelper.FileLog("Start Service Error：" + serviceName);
                        }
                    }
                }
                else
                {
                    LogHelper.FileLog(serviceName + " 已经启动");
                }

            }
            else
            {
                LogHelper.FileLog(serviceName + " 不存在");
            }
        }


        /// <summary>
        /// 关闭服务 
        /// </summary>
        /// <param name="serviceName"></param>
        public static void StopService(string serviceName)
        {
            if (IsServiceExisted(serviceName))
            {
                ServiceController service = new ServiceController(serviceName);
                if (service.Status == ServiceControllerStatus.Running && service.Status == ServiceControllerStatus.StartPending)
                {
                    service.Stop();
                    for (int i = 0; i < 10; i++)
                    {
                        service.Refresh();
                        System.Threading.Thread.Sleep(1000);
                        if (service.Status == ServiceControllerStatus.Stopped)
                        {
                            break;
                        }
                        if (i == 59)
                        {
                            throw new Exception("Start Service Error：" + serviceName);
                        }
                    }
                }
                else
                {
                    LogHelper.FileLog(serviceName + " 已经停止");
                }
            }
            else
            {
                LogHelper.FileLog(serviceName + " 不存在");
            }
        }

        /// <summary>
        /// 获取服务状态
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public static ServiceControllerStatus GetServiceStatus(string serviceName)
        {
            if (IsServiceExisted(serviceName))
            {
                ServiceController service = new ServiceController(serviceName);
                LogHelper.FileLog(serviceName + " 当前状态：" + service.Status.ToString());
                return service.Status;
            }
            else
            {
                return ServiceControllerStatus.Stopped;
            }

        }


        public static bool Install(string serviceName, string displayName = "", string desc = "")
        {
            if (IsServiceExisted(serviceName)) {
                LogHelper.FileLog(serviceName + "已经存在");
                return true;
            }

            try
            {
                TransactedInstaller ti = new TransactedInstaller();
                ti.Installers.Add(new ServiceProcessInstaller
                {
                    Account = ServiceAccount.LocalSystem,

                });
                string[] cmdline = { };
                string serviceFileName = Assembly.GetExecutingAssembly().Location;
                AssemblyInstaller assemblyInstaller = new AssemblyInstaller(serviceFileName, cmdline);
                var installer = new ServiceInstaller
                {
                    DisplayName = "",
                    ServiceName = serviceName,
                    Description = desc,
                    //ServicesDependedOn = new string[] { "MSSQLSERVER" },//前置服务
                    StartType = ServiceStartMode.Automatic,//运行方式                    
                };


                ti.Installers.Add(installer);
                ti.Context = new InstallContext();
                string args = " service";
                //ti.Context.Parameters["assemblypath"] = "\"" + Assembly.GetEntryAssembly().Location + " " + args;
                var path ="\""+ Assembly.GetEntryAssembly().Location + " \" " + args;
                ti.Context.Parameters["assemblypath"] = path;
                ti.Install(new Hashtable());
                LogHelper.FileLog("install service successed");
                return true;
            }
            catch (Exception ex)
            {
                var m = "install service Error:" + ex.Message;
                LogHelper.FileLog(m);
                return false;
            }

        }
        public static bool UnInstall(string serviceName)
        {
            if (!IsServiceExisted(serviceName))
            {
                LogHelper.FileLog(serviceName + "不存在");
                return false;
            }

            try
            {
                StopService(serviceName);

                TransactedInstaller ti = new TransactedInstaller();
                ti.Installers.Add(new ServiceProcessInstaller
                {
                    Account = ServiceAccount.LocalSystem
                });
                ti.Installers.Add(new ServiceInstaller
                {
                    DisplayName = "",
                    ServiceName = serviceName,
                    Description = MainWindow.description,
                    //ServicesDependedOn = new string[] { "MSSQLSERVER" },//前置服务
                    StartType = ServiceStartMode.Automatic//运行方式
                });
                ti.Uninstall(null);
                LogHelper.FileLog("Uninstall service successed");
                return true;
            }
            catch (Exception ex)
            {
                var m = "UnInstall service Error:" + ex.Message;
                LogHelper.FileLog(m);
                return false;
            }
        }

    }
}
